import React, { useEffect, useRef } from 'react';
import PropTypes from 'prop-types';
import { Button, Col, Empty, Form, Icon, Input, message, Row, Select, Typography } from 'antd';
import { useRequest, useDictionary, useDynamicList } from '@/hooks';
import moment from 'moment';
import { createDictionary } from '@/dictionary';
import { formatDateRange } from '@/utils/utils';
import RangePicker from '@/pages/Recruitment/containers/resume/RangePicker';
import FormContainer from './FormContainer';
import styles from './index.less';

const { Text } = Typography;

const RANGE_PICKER_FORMAT_YYYY_MM_DD = 'YYYY-MM-DD';

const [workExperienceList, getWorkExperienceText] = createDictionary('WORK_EXPERIENCE_DICT');

/**
 * 员工档案 - 工作经历
 */
const WorkExperienceSection = ({ formData, onChange, readonly, saveAction }) => {
    const formRef = useRef();
    // 提交
    const { run: submitRun } = useRequest(submitData => saveAction && saveAction(submitData), {
        manual: true
    });
    // 字典数据
    const [industryTypeList, getIndustryTypeText] = useDictionary('industryType');
    // 列表管理
    const {
        list: workList,
        remove: workListRemove,
        push: workListPush,
        getKey: workListGetKey,
        resetList: workListReset
    } = useDynamicList([]);

    useEffect(() => {
        // 重置列表的值
        workListReset(formData.workList);
    }, [workListReset, formData.workList]);

    useEffect(() => {
        // 表单赋值
        formRef.current.getFieldDecorator('workList', { initialValue: formData.workList || [] });
    }, [formData.workList]);

    // 保存
    const handleSubmit = async values => {
        const workListObject =
            values.workExperience === 1 &&
            workList.map((item, index) => {
                const key = workListGetKey(index);
                return {
                    startTime:
                        values.startTime[key]?.[0] && values.startTime[key][0].format(RANGE_PICKER_FORMAT_YYYY_MM_DD),
                    endTime:
                        values.startTime[key]?.[1] && values.startTime[key][1].format(RANGE_PICKER_FORMAT_YYYY_MM_DD),
                    organize: values.organize[key],
                    industry: values.industry[key],
                    salary: values.salary[key],
                    post: values.post[key],
                    reason: values.reason[key],
                    areaCode: values.areaCode[key],
                    approveName: values.approveName[key],
                    approvePhone: values.approvePhone[key]
                };
            });
        const submitData = Object.assign({
            employeeCode: formData.employeeCode,
            workExperience: values.workExperience,
            newList: workListObject || []
        });
        // 提交
        const res = await submitRun(submitData);
        if (res.code === 10000) {
            message.success(res.msg);
            onChange({
                workExperience: submitData.workExperience,
                workList: submitData.newList
            });
        } else {
            message.error(res.msg);
        }
    };

    // 取消编辑
    const handleCancel = () => {
        workListReset(formData.workList);
    };

    // 取消编辑
    const handleEdit = () => {
        if (workList.length === 0) {
            workListPush({});
        }
    };

    // 处理日期为空的情况
    const preprocessDateRange = (startDate, endDate) => [startDate && moment(startDate), endDate && moment(endDate)];

    // render
    return (
        <FormContainer
            ref={formRef}
            title="工作经验"
            hasEditAuth={!readonly && !!saveAction}
            onSubmit={handleSubmit}
            onCancel={handleCancel}
            onEdit={handleEdit}
        >
            {({ getFieldDecorator, getFieldValue }, editStatus) => (
                <div className={styles.dynamicList}>
                    <Row gutter={24} style={{ marginBottom: '10px' }}>
                        <Col span={12}>
                            <Form.Item label="工作经验">
                                {editStatus ? (
                                    getFieldDecorator('workExperience', {
                                        initialValue: formData?.workExperience || undefined,
                                        rules: [
                                            {
                                                required: true,
                                                message: '请选择工作经验'
                                            }
                                        ]
                                    })(
                                        <Select placeholder="请选择工作经验">
                                            {workExperienceList?.map(item => (
                                                <Select.Option value={item.value} key={item.value}>
                                                    {item.text}
                                                </Select.Option>
                                            ))}
                                        </Select>
                                    )
                                ) : (
                                    <Text>{getWorkExperienceText(formData?.workExperience)}</Text>
                                )}
                            </Form.Item>
                        </Col>
                    </Row>
                    {(editStatus ? getFieldValue('workExperience') : formData?.workExperience) === 1 && (
                        <>
                            {workList.length === 0 && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />}
                            <div className={styles.dynamicListContainer}>
                                {workList.map((item, index) => (
                                    <div key={workListGetKey(index)} className={styles.dynamicListItem}>
                                        {editStatus && (
                                            <Icon
                                                onClick={() => workListRemove(index)}
                                                className={styles.dynamicListClose}
                                                type="close-circle"
                                                theme="filled"
                                            />
                                        )}
                                        <Row gutter={24}>
                                            <Col span={12}>
                                                <Form.Item label="起止时间">
                                                    {editStatus ? (
                                                        getFieldDecorator(`startTime[${workListGetKey(index)}]`, {
                                                            initialValue: preprocessDateRange(
                                                                item?.startTime,
                                                                item?.endTime
                                                            ),
                                                            rules: [
                                                                {
                                                                    required: true,
                                                                    message: '请选择起止时间',
                                                                    validator(rule, value, callback) {
                                                                        if (value && value[0]) {
                                                                            callback();
                                                                        } else {
                                                                            callback('请选择起止时间');
                                                                        }
                                                                    }
                                                                }
                                                            ]
                                                        })(<RangePicker />)
                                                    ) : (
                                                        <Text>
                                                            {formatDateRange(
                                                                item?.startTime,
                                                                item?.endTime,
                                                                'YYYY-MM-DD'
                                                            )}
                                                        </Text>
                                                    )}
                                                </Form.Item>
                                                <Form.Item label="行业/主营业务">
                                                    {editStatus ? (
                                                        getFieldDecorator(`industry[${workListGetKey(index)}]`, {
                                                            initialValue: item?.industry || undefined,
                                                            rules: [
                                                                {
                                                                    required: true,
                                                                    message: '请选择行业/主营业务'
                                                                }
                                                            ]
                                                        })(
                                                            <Select placeholder="请输入行业/主营业务">
                                                                {industryTypeList?.map(v => (
                                                                    <Select.Option value={v?.value} key={v?.value}>
                                                                        {v?.text}
                                                                    </Select.Option>
                                                                ))}
                                                            </Select>
                                                        )
                                                    ) : (
                                                        <Text>{getIndustryTypeText(item?.industry)}</Text>
                                                    )}
                                                </Form.Item>
                                                <Form.Item label="离职原因">
                                                    {editStatus ? (
                                                        getFieldDecorator(`reason[${workListGetKey(index)}]`, {
                                                            initialValue: item?.reason ?? undefined,
                                                            rules: [
                                                                {
                                                                    required: true,
                                                                    message: '请输入离职原因'
                                                                },
                                                                { max: 50, message: '字数不能超过50个字符' }
                                                            ]
                                                        })(<Input placeholder="请输入离职原因" maxLength={50} />)
                                                    ) : (
                                                        <div className="multiLineText">{item?.reason}</div>
                                                    )}
                                                </Form.Item>
                                                <Form.Item label="证明人">
                                                    {editStatus ? (
                                                        getFieldDecorator(`approveName[${workListGetKey(index)}]`, {
                                                            initialValue: item?.approveName ?? undefined,
                                                            rules: [
                                                                {
                                                                    required: true,
                                                                    message: '请输入证明联系人'
                                                                },
                                                                { max: 50, message: '字数不能超过50个字符' }
                                                            ]
                                                        })(<Input maxLength={50} placeholder="请输入证明联系人" />)
                                                    ) : (
                                                        <div className="multiLineText">{item?.approveName}</div>
                                                    )}
                                                </Form.Item>
                                            </Col>
                                            <Col span={12}>
                                                <Form.Item label="工作单位">
                                                    {editStatus ? (
                                                        getFieldDecorator(`organize[${workListGetKey(index)}]`, {
                                                            initialValue: item?.organize ?? undefined,
                                                            rules: [
                                                                {
                                                                    required: true,
                                                                    message: '请输入工作单位'
                                                                },
                                                                {
                                                                    pattern: /^[^\s]+(\s+[^\s]+)*$/,
                                                                    message: '此处不能输入空格'
                                                                },
                                                                {
                                                                    min: 1,
                                                                    max: 50,
                                                                    message: '请输入1~50个字符'
                                                                }
                                                            ]
                                                        })(<Input placeholder="请输入工作单位" />)
                                                    ) : (
                                                        <div className="multiLineText">{item?.organize}</div>
                                                    )}
                                                </Form.Item>
                                                <Form.Item label="职位职级">
                                                    {editStatus ? (
                                                        getFieldDecorator(`post[${workListGetKey(index)}]`, {
                                                            initialValue: item?.post ?? undefined,
                                                            rules: [
                                                                {
                                                                    required: true,
                                                                    message: '请输入职位职级'
                                                                },
                                                                {
                                                                    min: 1,
                                                                    max: 50,
                                                                    message: '请输入1~50个字符'
                                                                },
                                                                {
                                                                    pattern: /^[^\s]+(\s+[^\s]+)*$/,
                                                                    message: '此处不能输入空格'
                                                                }
                                                            ]
                                                        })(<Input placeholder="请输入职位职级" />)
                                                    ) : (
                                                        <div className="multiLineText">{item?.post}</div>
                                                    )}
                                                </Form.Item>
                                                <Form.Item label="离职薪资">
                                                    {editStatus ? (
                                                        getFieldDecorator(`salary[${workListGetKey(index)}]`, {
                                                            initialValue: item?.salary ?? undefined
                                                        })(<Input placeholder="请输入离职薪资" />)
                                                    ) : (
                                                        <Text>{item?.salary}</Text>
                                                    )}
                                                </Form.Item>
                                                <Form.Item label="证明人联系方式">
                                                    {editStatus ? (
                                                        getFieldDecorator(`approvePhone[${workListGetKey(index)}]`, {
                                                            initialValue: item?.approvePhone ?? undefined,
                                                            rules: [
                                                                {
                                                                    validator(rule, value, callback) {
                                                                        const regex = /^\d{7,11}$/;
                                                                        if (!value) {
                                                                            callback();
                                                                        } else if (!regex.test(value)) {
                                                                            callback('只能输入7-11位数字');
                                                                        }
                                                                        callback();
                                                                    }
                                                                }
                                                            ]
                                                        })(
                                                            <Input
                                                                maxLength={20}
                                                                placeholder="请输入联系人电话"
                                                                addonBefore={getFieldDecorator(
                                                                    `areaCode[${workListGetKey(index)}]`,
                                                                    {
                                                                        initialValue:
                                                                            workList[workListGetKey(index)]?.areaCode ||
                                                                            '86'
                                                                    }
                                                                )(
                                                                    <Select placeholder="区号" style={{ width: 80 }}>
                                                                        <Select.Option value="86">+86</Select.Option>
                                                                        <Select.Option value="65">+65</Select.Option>
                                                                    </Select>
                                                                )}
                                                            />
                                                        )
                                                    ) : (
                                                        <Text>
                                                            {item.approvePhone
                                                                ? `${item.areaCode ? `+${item.areaCode}` : ''} ${
                                                                      item.approvePhone
                                                                  }`
                                                                : '--'}
                                                        </Text>
                                                    )}
                                                </Form.Item>
                                            </Col>
                                        </Row>
                                    </div>
                                ))}
                            </div>
                            {editStatus && workList.length < 10 ? (
                                <Button style={{ marginTop: '20px' }} block onClick={() => workListPush({})}>
                                    +添加工作经历
                                </Button>
                            ) : null}
                        </>
                    )}
                </div>
            )}
        </FormContainer>
    );
};

// prop
WorkExperienceSection.propTypes = {
    formData: PropTypes.object.isRequired,
    onChange: PropTypes.func.isRequired,
    saveAction: PropTypes.func,
    readonly: PropTypes.bool
};

WorkExperienceSection.defaultProps = {
    saveAction: null,
    readonly: false
};

export default WorkExperienceSection;
